<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style>
        #space {
            background-color: darkgray;
            border: 1px solid #000;
            margin: auto;
        }

        .user {
            width: 300px;
            height: 200px;
            background-color: aqua;
            border: 1px solid #000;
            border-radius:30px;
            float: left;
            margin: 30px;
        }

        .user span{
            margin-left: 20px;
            font-size: 15px;
        }

        .message {
            width: 298px;
            height: 131px;
        }
    </style>

    <link rel="stylesheet" href="gf_style/gf_css.css">

    <!--引入bootstrap-->
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link href="gf_style/toastr.css" rel="stylesheet"/>

    <script
            src="http://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <!-- 引入bootstrap -->
    <script src="gf_style/toastr.js"></script>
</head>
<body>
<h2>WebSocket</h2>
<div id="control" >
    <form class="form-horizontal">
        <div class="form-group">
            <form class="form-inline">
                <button type="button"  onclick="begin()" class="btn btn-primary">开启会话</button>
                <button type="button"  onclick="end()" class="btn btn-primary">关闭会话</button>
                <button type="button"  onclick="getAllUser()" class="btn btn-primary">查看所有用户</button>
                <button type="button"  onclick="sendAll()" class="btn btn-primary">公告</button>
            </form>
        </div>
        <div class="form-group">
            <form class="form-inline">
                <input id="sendMessageUserId" type="text" placeholder="id" class="form-control">
                <input id="sendMessage" type="text" placeholder="message" class="form-control">
                <button onclick="sendOne()" type="button" class="btn btn-primary">发送信息</button>
            </form>
        </div>
        <div class="form-group">
            <form class="form-inline">
                <input id="replyId" type="text" placeholder="id" class="form-control">
                <input id="replyMessage" type="text" placeholder="message" class="form-control">
                <button onclick="replyOne()" type="button" class="btn btn-primary">回复</button>
            </form>
        </div>
        <div class="form-group">
            <form class="form-inline">
                <input id="newUserId" type="text" placeholder="new user id" class="form-control">
                <input id="newUserName" type="text" placeholder="new user name" class="form-control">
                <button onclick="addUser()" type="button" class="btn btn-success">创建用户</button>
            </form>
        </div>
        <div class="form-group">
            <form class="form-inline">
                <input id="delUserId" type="text" placeholder="user id" class="form-control">
                <button onclick="delUser()" type="button" class="btn btn-danger">删除用户</button>
            </form>
        </div>
    </form>
</div>
<div id="space"></div>
</body>
<script>

    port = 2048;
    begin(port);
    getAllUser();

    function replyOne() {
        var replyId = $("#replyId").val();
        var message = $("#replyMessage").val();
        var o = buildMessage(2,replyId,message);
        $.get("/netty/replyOne?message="+o);
        console.log("回复:" + o);
    }
    // 公告
    function replyAll() {
        alert("sendAll");
    }

    // 开启会话
    function begin(port) {
        $.get("/netty/begin?port="+port);
        message.success("开启会话成功！");
    }

    // 关闭会话
    function end() {
        alert("end");
    }

    // 查看所有用户
    function getAllUser() {
        $.get("/netty/getAllUser",function(data){
            var users = data.data;
            $("#user").html("");
            $("#space").html("");
            for (var i = 0; i<users.length;i++){
                // var newWebSocket = addUser(users[i].id,users[i].name);
                var newWebSocket = drawNewUser(users[i].id,users[i].name);
                socket.push(newWebSocket) ;
            }
        });
    }




    // 私聊
    function sendOne() {
        var message = $("#sendMessage").val();
        var userId = $("#sendMessageUserId").val();
        var o = buildMessage(userId,message);
        websocket.send(o);
        console.log("发送信息"+o);
    }
    // 公告
    function sendAll() {
        $.get("/netty/sendAll",function(data){

        }
    }

    var socket = new Array();

    // 创建用户
    function addUser(id,name) {
        if (id === undefined) {
            id = $("#newUserId").val();
        }
        if (name === undefined) {
            name = $("#newUserName").val();
        }
        if (id === '') {
            id = Math.round(Math.random()*10000);
        }
        if (name === '') {
            name = Math.round(Math.random()*1000000);
        }
        var websocket = new WebSocket("ws://localhost:"+port+"/ws");
        websocket.onopen = function() {
            //成功连接到服务器
            websocket.send(buildMessage(1, id, name));
            drawNewUser(id,name);
            $("#newUserId").val("");
            $("#messageLog_"+id).val("message:");
        };
        websocket.onmessage = function (ev) {
            message.info(ev.data);
            var tempMessage = $("#messageLog_"+id).val();
            console.log(tempMessage);
            $("#messageLog_"+id).val("收到："+tempMessage+"\n"+ev.data);
            console.log();
        };
        websocket.onerror = function (ev) {
            message.error("出现故障");
        };
        websocket.onclose = function (ev) {
            message.info("链接关闭");
        };
        return websocket;
    }


    function drawNewUser(id,name) {
        $("#space").append("" +
            "<div id='user_" + id + "' class='user'>" +
            "<span id='userId'>userId:"+id+"</span>" +
            "<br/>" +
            "<span id='userName'>userName:"+name+"</span>" +
            "<br/>" +
            "<textarea class='message' disabled id='messageLog_"+id+"' />" +
            "</div>" +
            "");
    }

    // 删除用户
    function delUser() {
        var id = $("#delUserId").val();
        $("#user_" + id).remove();
        $("#delUserId").val("");
        getAllUser();
    }

    /*
        1：加入聊天
        2：发送信息
        3：回复信息
     */
    function buildMessage(type,id,message) {
        var obj = {};
        obj.type=type;
        obj.message = message;
        obj.id = id;
        return encodeURI(JSON.stringify(obj));
    }


</script>
</html>
